package com.tongtailian.www.stir.utils.crash;

import android.androidlib.utils.StringUtils;
import android.androidlib.utils.SystemUtils;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;


import com.tencent.bugly.crashreport.CrashReport;
import com.tongtailian.www.stir.MyApplication;
import com.tongtailian.www.stir.activity.CrashDialogActivity;
import com.tongtailian.www.stir.utils.PushLog;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;


/**
 * 功能描述：系统崩溃集中处理类
 */


public class CrashHandler implements Thread.UncaughtExceptionHandler {
    private static CrashHandler instance;
    private Application application;
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    private int MAX_POST_NUM = 5;
    private int postNum;

    /**
     * 保证只有一个CrashHandler实例
     */
    private CrashHandler(Context context) {
        application = (Application) context.getApplicationContext();
    }

    /**
     * 获取CrashHandler实例 ,单例模式
     */
    public static CrashHandler getInstance() {
        CrashHandler inst = instance;
        if (inst == null) {
            synchronized (CrashHandler.class) {
                inst = instance;
                if (inst == null) {
                    inst = new CrashHandler(MyApplication.getInstance());
                    instance = inst;
                }
            }
        }
        return inst;
    }

    public void init(){
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * 当UncaughtException发生时会转入该函数来处理
     */
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {

            if (!handleException(ex) && mDefaultHandler != null) {
                // 如果用户没有处理则让系统默认的异常处理器来处
                mDefaultHandler.uncaughtException(thread, ex);
            }else{
                // 跳转到崩溃提示Activity
                Intent intent = new Intent(application, CrashDialogActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                application.startActivity(intent);
                System.exit(0);
            }


    }


    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }

        // 收集错误信息
        String uncaughtExceptionString = getCrashInfo(ex);

        if(StringUtils.isNotEmpty(uncaughtExceptionString))
                CrashReport.postCatchedException(ex);

        return true;
    }

    private String getCrashInfo(Throwable ex) {
        try {
            StringWriter sw = new StringWriter();
            ex.printStackTrace(new PrintWriter(sw, true));
            PackageManager packageManager = application.getPackageManager();
            // getPackageName()是你当前类的包名，0代表是获取版本信息
            PackageInfo packInfo;
            packInfo = packageManager.getPackageInfo(application.getPackageName(),
                    0);
            String version = packInfo.versionName;//获取版本号
            String str = sw.toString();//详细错误日志
            String uncaughtExceptionString = "崩溃异常：异常版本："+ version +"    系统版本："+ SystemUtils.getMobileSysVersion()+ "\n" + str;
            PushLog.info(uncaughtExceptionString);

            return uncaughtExceptionString;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}

